<template>
  <view class="wrap">
    <view class="pox" :style="`height: calc(35px + ${statusBarHeight} + 20rpx)`">
      <status-bar></status-bar>
      <view class="head-nav" :style="{top: statusBarHeight}">
        <view class="search">
          <uv-input v-model="search" placeholder="搜索社群，用户或内容" border='none' fontSize='28rpx' color='#000' prefixIcon='search' confirmType='search' prefixIconStyle='color: #999999;font-size: 42rpx;' placeholderStyle='font-size: 28rpx;color: #9C9C9C;font-weight: 400;' :customStyle="{backgroundColor: '#F5F5F5', height: '64rpx', paddingLeft: '18rpx'}" @confirm='searchKey'></uv-input>
        </view>
        <view class="select" @click="goBack">取消</view>
      </view>
    </view>
    <view class="body" v-if="show">
      <template v-if="history.length">
        <view class="history">
          <view class="left">最近搜索</view>
          <view class="icon" @click="clearSearch">
            <image src="../../static/history.png" class="img"></image>
          </view>
        </view>
        <view class="storage">
          <view class="row" v-for="(item,index) in history" :key="index" @click="getWord(item)">
            {{ item.length > 8 ? (item.slice(0, 8) + '...') : item }}
          </view>
        </view>
      </template>
      <view class="recommend">
        <view class="title">推荐社群</view>
        <view class="group">
          <view class="item" v-for="(item,index) in recommend" :key="index" @click="tapClick(item)">
            <view class="user">
              <view class="rank" v-if="index > 2">{{ index + 1 }}</view>
              <view class="rank" v-else>
                <image src="../../static/one.png" class="img" v-if="index == 0"></image>
                <image src="../../static/two.png" class="img" v-if="index == 1"></image>
                <image src="../../static/three.png" class="img" v-if="index == 2"></image>
              </view>
              <view class="avatar">
                <image :src="setUrl(item.logo_image)" class="img" mode="aspectFill"></image>
              </view>
              <view class="name">{{ item.name }}</view>
            </view>
            <uv-icon name="arrow-right" color='#B8B8B8' size='30rpx'></uv-icon>
          </view>
        </view>
      </view>
    </view>
    <template v-else>
      <uv-tabs :list="tabList" :current='active' itemStyle='height: 90rpx' :scrollable='false' lineColor='#E43222' lineWidth='36rpx' lineHeight='6rpx' inactiveStyle='font-weight: 500; font-size: 28rpx; color: #999999;' activeStyle='font-weight: 500; font-size: 28rpx; color: #2B2B2B;' @click="tabClick"></uv-tabs>
      <uv-line hairline></uv-line>
      <view class="body">
        <view class="list" v-if="active == 0">
          <group v-for="(item, index) in list" :key="index" :detail='item'></group>
        </view>
        <view class="list" v-if="active == 1">
          <people v-for="(item, index) in list" :key="index" :detail='item'></people>
        </view>
        <view class="list" v-if="active == 2">
          <news :detail='item' v-for="(item, index) in list" :key="index" @followClick='followClick'></news>
        </view>
        <view class="list" v-if="active == 3">
          <course :detail='item' v-for="(item,index) in list" :key="index"></course>
        </view>
        <view class="list" v-if="active == 4">
          <live :detail='item' v-for="(item,index) in list" :key="index"></live>
        </view>
        <uv-empty :show='showLeng' mode="list" marginTop='200rpx'></uv-empty>
      </view>
    </template>
    
    <uv-modal ref="modal" title="提示" content='是否清空搜索历史？' showCancelButton confirmColor='#E43222' @confirm="confirm"></uv-modal>
  </view>
</template>

<script setup>
import group from '../../components/search/group.vue';
import people from '../../components/search/people.vue';
import news from '../../components/dynamic/news.vue';
import course from '../../components/lesearch/course.vue';
import live from '../../components/myTheme/live.vue';
import { ref } from "vue"
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
import { deepArr, setUrl, loading } from '@/common';
import { post, get } from '@/api';

const statusBarHeight = uni.getSystemInfoSync().statusBarHeight + 'px';
const modal = ref(null);

let search = ref('');
let tabList = [{name: '社群'},{name: '用户'},{name: '资讯'},{name: '课程'},{name: '直播'}];
let active = ref(0);
let history = ref([]);
let recommend = ref([]);
let list = ref([]);
let last_page = 0;
let page = 1;
let limit = 15;
let showLeng = ref(false);
let show = ref(true);

onLoad((option) => {
  const historyStorage = uni.getStorageSync('historyIndex');
  if(historyStorage){
    history.value = deepArr(historyStorage);
  }
  getList();
})
// 下拉刷新
onPullDownRefresh(() => {
  page = 1
  list.value = [];
  if(active.value == 3){
    getResearchList();
  }else if(active.value == 2){
    getNewList();
  }else{
    getSearchList();
  }
  setTimeout(() => {
    uni.stopPullDownRefresh()
  }, 1000)
})
// 上拉加载
onReachBottom(async () => {
  if(last_page < page || last_page == page) return;
  page++
  if(active.value == 3){
    getResearchList();
  }else if(active.value == 2){
    getNewList();
  }else{
    getSearchList();
  }
})

// 默认的推荐社群信息
function getList(){
  const params = {
    page: 1,
    limit: 10
  }
  post('api/association/recommendAssociationList', params).then(res => {
    if(res.code == 1){
      const { data } = res.data;
      recommend.value = data;
    }
  })
}
// 搜索结果列表
function getSearchList(){
  const params = {
    page,
    limit,
    type: active.value + 1,
    search_text: search.value
  }
  post('api/association/search', params).then(res => {
    if(res.code == 1){
      const data = res.data;
      last_page = data.last_page;
      list.value = [...list.value, ...data.data];
      if(list.value.length){
        showLeng.value = false;
      }else{
        showLeng.value = true;
      }
    }
  })
}
// 搜索结果动态
function getNewList(){
  const params = {
    page,
    limit,
    display: 0,
    type: 0,
    search_text: search.value
  }
  post('api/news/getNewsList', params).then(res => {
    if(res.code == 1){
      const data = res.data;
      last_page = data.last_page;
      list.value = [...list.value, ...data.data];
      if(list.value.length){
        showLeng.value = false;
      }else{
        showLeng.value = true;
      }
    }
  })
}
// 搜索结果：课程
function getResearchList(){
  const params = {
    page,
    pagePer: limit,
    keyword: search.value
  }
  get('/api/lesson/search', params).then(res => {
    if(res.code == 1){
      const data = res.data;
      last_page = data.last_page;
      list.value = [...list.value, ...data.data];
      if(list.value.length){
        showLeng.value = false;
      }else{
        showLeng.value = true;
      }
    }
  })
}
function getLiveList(){
  const params = {
    page,
    pagePer: limit,
    keyword: search.value
  }
  get('/api/Live/searchLiveList', params).then(res => {
    if(res.code == 1){
      const data = res.data;
      last_page = data.last_page;
      list.value = [...list.value, ...data.data];
      if(list.value.length){
        showLeng.value = false;
      }else{
        showLeng.value = true;
      }
    }
  })
}
// 记录搜索词
function searchKey(){
  const historyStorage = uni.getStorageSync('historyIndex');
  let arr = [];
  if(historyStorage){
    arr = deepArr(historyStorage);
    const index = arr.findIndex(o => o == search.value);
    if(index >= 0){
      arr.splice(index, 1);
      arr = [search.value, ...arr];
    }else{
      arr = [search.value, ...arr];
      if(arr.length > 10){
        arr.pop();
      }
    }
  }else{
    arr.push(search.value);
  }
  uni.setStorageSync('historyIndex', arr);
  history.value = arr;
  
  page = 1;
  list.value = [];
  show.value = false; // 隐藏推荐和历史记录
  
  if(active.value == 3){
    getResearchList();
  }else if(active.value == 2){
    getNewList();
  }else if(active.value == 4){
    getLiveList();
  }else{
    getSearchList();
  }
}
// 清空历史记录弹窗
function clearSearch(){
  modal.value.open();
}
// 确认清空历史记录
function confirm(){
  history.value = [];
  uni.removeStorageSync('historyIndex');
}
function getWord(value){
  show.value = false;
  active.value = 0;
  search.value = value;
  if(active.value == 3){
    getResearchList();
  }else if(active.value == 2){
    getNewList();
  }else if(active.value == 4){
    getLiveList();
  }else{
    getSearchList();
  }
}
function tabClick(row){
  page = 1;
  list.value = [];
  active.value = row.index;
  show.value = false;
  if(active.value == 3){
    getResearchList();
  }else if(active.value == 2){
    getNewList();
  }else if(active.value == 4){
    getLiveList();
  }else{
    getSearchList();
  }
}
function followClick(row){
  list.value.forEach(e => {
    if(row.userId == e.user.id){
      e[row.type] = e[row.type] == 1 ? 0 : 1;
    }
  })
}
function tapClick(row){
  if(row.is_expire){
    msg.value = '该社群已到期，请联系管理员';
    modal.value.open();
    return;
  }
  const url = row.apply_status == 2 ? '/pages/group/yes-detail' : '/pages/group/not-detail'
  uni.navigateTo({
    url: `${url}?id=${row.id}`
  });
}
function goBack(){
  uni.navigateBack({
    delta: 1
  });
}
</script>

<style lang="scss" scoped>
  .body{
    padding: 0 30rpx;
    .list{
      padding-top: 40rpx;
    }
    .recommend{
      .group{
        padding-top: 24rpx;
        .item{
          width: 100%;
          margin-bottom: 40rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .user{
            display: flex;
            align-items: center;
            flex: 1;
            width: 0;
            .name{
              font-weight: 400;
              font-size: 32rpx;
              color: #2B2B2B;
            }
            .avatar{
              width: 70rpx;
              height: 70rpx;
              border-radius: 10rpx;
              font-size: 0;
              margin-left: 32rpx;
              margin-right: 20rpx;
            }
            .rank{
              font-weight: 600;
              font-size: 28rpx;
              color: #2B2B2B;
              width: 40rpx;
              text-align: center;
              .img{
                width: 40rpx;
                height: 40rpx;
              }
            }
          }
        }
      }
      .title{
        font-weight: 500;
        font-size: 32rpx;
        color: #2B2B2B;
        padding-top: 60rpx;
      }
    }
    .storage{
      width: 100%;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .row{
        font-weight: 400;
        font-size: 28rpx;
        color: #2B2B2B;
        height: 64rpx;
        line-height: 64rpx;
        border-radius: 64rpx;
        background: #F5F5F5;
        padding: 0 24rpx;
        margin-top: 24rpx;
        margin-right: 24rpx;
      }
    }
    .history{
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      padding-top: 45rpx;
      .icon{
        width: 32rpx;
        height: 32rpx;
        font-size: 0;
      }
      .left{
        font-weight: 500;
        font-size: 32rpx;
        color: #2B2B2B;
      }
    }
  }
  .pox{
    position: relative;
    z-index: 2;
    .head-nav{
      width: 100%;
      padding: 0 30rpx;
      padding-top: 20rpx;
      display: flex;
      align-items: center;
      .select{
        margin-left: 30rpx;
        color: #737373;
        font-weight: 400;
        font-size: 28rpx;
      }
      .search{
        overflow: hidden;
        border-radius: 100rpx;
        flex: 1;
      }
    }
  }
</style>